package fenxiaoCheckClassId;

import bmCheckClassId.database.Database;
import bmCheckClassId.database.DatabaseMysql;
import com.rslai.commons.util.FileUtil;
import com.rslai.commons.util.StringUtil;
import com.rslai.commons.util.excel.ExcelWrite;
import com.rslai.commons.util.excel.Head;
import com.rslai.commons.util.excel.exception.ExcelException;
import org.apache.commons.lang3.ArrayUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;


/**
 * Created by rslai on 2018/12/12.
 */
public class fenxiaoCheck {
    public void check() throws IOException {
        Database database = new DatabaseMysql("127.0.0.1", 3306, "jianzhang", "root", "123456"); // 创建数据库对象

        FileUtil fileUtil = new FileUtil();
        fileUtil.mkdirs("./output");

        try {
            ExcelWrite excelWrite = this.createExcel();

            ResultSet rs = database.query("SELECT  * FROM `sheet` WHERE url LIKE \"%bj.%\"");

            while (rs.next()) {
                String url = rs.getString("url");
                String host = rs.getString("host");

                if (StringUtil.isNotBlank(url)) {
                    System.out.println("正在处理 " + url);

                    String[] tmp = new String[3];

                    tmp[0] = url;
                    tmp[1] = host;

                    List<String> eBC = new LinkedList<String>();
                    //this.checkWebPage(url, url, expect, eBC);
                    this.checkWebPage(url, url, new String[]{"https://www.huatu.com/images/js/shence.js", "http://www.huatu.com/images/js/click_com.js"}, eBC);

                    if (eBC.size() != 0) {
                        tmp[2] = ArrayUtils.toString(eBC);
                        excelWrite.addBody(tmp); // 添加一行
                    }
                }
            }

            // 保存到excel
            FileOutputStream fos = new FileOutputStream("./output/checkList.xls");
            excelWrite.write(fos);
            fos.close();

            System.out.println("检查完毕！结果在：./output/checkList.xls");
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ExcelException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据url遍历查找是否包括指定内容
     * @param parentUrl 父目录url
     * @param url url（要检查的url）
     * @param expect 不想包括的内容
     * @param errorBC 如果错了存在这里
     */
    private void checkWebPage(String parentUrl, String url, String[] expect, List<String> errorBC) {
        //ExcelWrite excelWrite, String cityName, String parentUrl, String cityURL
        //System.out.println(parentUrl);
        Document doc = null;
        try {
            doc = Jsoup.connect(url).maxBodySize(0).get();

            checkBC(doc.html(), expect, errorBC); // 拿到一个页面遍历里边是否有埋点的js文件
        } catch (Exception e) {
            //e.printStackTrace();
            if (e.toString().indexOf("Status=404") >= 0) {
                errorBC.add("404");
            }

        }
    }

    /**
     * 在页面源码中匹配有没有bc编号
     * @param str 源码
     * @param expect 希望不出现的
     * @param errorBC 如果出现保存在此处
     */
    private void checkBC(String str, String[] expect, List<String> errorBC) {
        for (String ex : expect) {
            if (str.toLowerCase().indexOf(ex.toLowerCase()) != -1) {
                return;
            }
        }
        errorBC.add("未找到埋点js");
    }

    /**
     * 将逗号分割文件改为数组
     * @param str
     * @return
     */
    private String[] toArray(String str) {
        LinkedList<String> list = new LinkedList<String>();
        for(String s : str.split(",")) {
            if (StringUtil.isNotBlank(s)) {
                list.add(s);
            }
        }

        String s[] = new String[list.size()];

        for (int i=0; i<list.size(); i++) {
            s[i] = list.get(i);
        }
        return s;
    }

    /**
     * 创建课程列表excel
     * @return excel对象
     * @throws com.rslai.commons.util.excel.exception.ExcelException
     */
    private ExcelWrite createExcel() throws ExcelException {
        ExcelWrite excelWrite = new ExcelWrite();
        Head head;
        head = new Head(0, "URL", 80, null);
        excelWrite.addHead(head);
        head = new Head(1, "HOST", 25, null);
        excelWrite.addHead(head);
        head = new Head(2, "错误", 50, null);
        excelWrite.addHead(head);
        return excelWrite;
    }

    public static void main(String[] args) throws IOException {
        FileUtil fileUtil = new FileUtil();
        fileUtil.mkdirs("./output");

        new fenxiaoCheck().check(); // 使用开发给的excel表检查课程id
    }

}
